import { useState } from "react";
import { motion } from "motion/react";
import { Button } from "./ui/button";
import { Card } from "./ui/card";
import { Badge } from "./ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Textarea } from "./ui/textarea";
import { Switch } from "./ui/switch";
import { Slider } from "./ui/slider";
import { ProviderSettingsSection } from './settings/providers/ProviderSettingsSection';
import { 
  Settings, 
  User, 
  Bot, 
  Palette, 
  Globe, 
  Shield, 
  Database,
  Download,
  Upload,
  RefreshCw,
  Save,
  RotateCcw
, Cloud
} from "lucide-react";

interface SettingsPanelProps {
  isOpen: boolean;
  onClose: () => void;
  initialTab?: 'general' | 'chat' | 'appearance' | 'privacy' | 'advanced' | 'providers';
}

interface AppSettings {
  theme: 'light' | 'dark' | 'system';
  language: string;
  fontSize: number;
  autoSave: boolean;
  notifications: boolean;
  soundEnabled: boolean;
  animationsEnabled: boolean;
}

interface ChatSettings {
  maxTokens: number;
  temperature: number;
  streamingEnabled: boolean;
  autoScroll: boolean;
  showTimestamps: boolean;
  compactMode: boolean;
  codeHighlighting: boolean;
}

interface PrivacySettings {
  dataCollection: boolean;
  crashReporting: boolean;
  analytics: boolean;
  shareUsageData: boolean;
}

export function SettingsPanel({ isOpen, onClose, initialTab }: SettingsPanelProps) {
  const [activeTab, setActiveTab] = useState<'general' | 'chat' | 'appearance' | 'privacy' | 'advanced' | 'providers'>(initialTab || 'general');
  const [hasChanges, setHasChanges] = useState(false);
  
  // 设置状态
  const [appSettings, setAppSettings] = useState<AppSettings>({
    theme: 'system',
    language: 'zh-CN',
    fontSize: 14,
    autoSave: true,
    notifications: true,
    soundEnabled: true,
    animationsEnabled: true,
  });

  const [chatSettings, setChatSettings] = useState<ChatSettings>({
    maxTokens: 4000,
    temperature: 0.7,
    streamingEnabled: true,
    autoScroll: true,
    showTimestamps: true,
    compactMode: false,
    codeHighlighting: true,
  });

  const [privacySettings, setPrivacySettings] = useState<PrivacySettings>({
    dataCollection: false,
    crashReporting: true,
    analytics: false,
    shareUsageData: false,
  });

  // 处理设置更改
  const handleAppSettingChange = (key: keyof AppSettings, value: any) => {
    setAppSettings(prev => ({ ...prev, [key]: value }));
    setHasChanges(true);
  };

  const handleChatSettingChange = (key: keyof ChatSettings, value: any) => {
    setChatSettings(prev => ({ ...prev, [key]: value }));
    setHasChanges(true);
  };

  const handlePrivacySettingChange = (key: keyof PrivacySettings, value: any) => {
    setPrivacySettings(prev => ({ ...prev, [key]: value }));
    setHasChanges(true);
  };

  // 保存设置
  const handleSaveSettings = async () => {
    try {
      // 这里应该调用 API 保存设置
      console.log('Saving settings:', { appSettings, chatSettings, privacySettings });
      setHasChanges(false);
    } catch (error) {
      console.error('Failed to save settings:', error);
    }
  };

  // 重置设置
  const handleResetSettings = () => {
    setAppSettings({
      theme: 'system',
      language: 'zh-CN',
      fontSize: 14,
      autoSave: true,
      notifications: true,
      soundEnabled: true,
      animationsEnabled: true,
    });
    setChatSettings({
      maxTokens: 4000,
      temperature: 0.7,
      streamingEnabled: true,
      autoScroll: true,
      showTimestamps: true,
      compactMode: false,
      codeHighlighting: true,
    });
    setPrivacySettings({
      dataCollection: false,
      crashReporting: true,
      analytics: false,
      shareUsageData: false,
    });
    setHasChanges(true);
  };

  // 导出设置
  const handleExportSettings = () => {
    const settings = { appSettings, chatSettings, privacySettings };
    const blob = new Blob([JSON.stringify(settings, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'iroh-rig-settings.json';
    a.click();
    URL.revokeObjectURL(url);
  };

  // 导入设置
  const handleImportSettings = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const settings = JSON.parse(e.target?.result as string);
        if (settings.appSettings) setAppSettings(settings.appSettings);
        if (settings.chatSettings) setChatSettings(settings.chatSettings);
        if (settings.privacySettings) setPrivacySettings(settings.privacySettings);
        setHasChanges(true);
      } catch (error) {
        console.error('Failed to import settings:', error);
      }
    };
    reader.readAsText(file);
  };

  if (!isOpen) return null;

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
      onClick={onClose}
    >
      <motion.div
        initial={{ scale: 0.95, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        exit={{ scale: 0.95, opacity: 0 }}
        className="bg-white dark:bg-slate-900 rounded-xl shadow-2xl border border-slate-200 dark:border-slate-700 w-full max-w-4xl h-[80vh] flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-slate-200 dark:border-slate-700">
          <div className="flex items-center gap-3">
            <Settings className="w-6 h-6 text-blue-500" />
            <div>
              <h2 className="text-xl font-semibold text-slate-900 dark:text-white">
                应用设置
              </h2>
              <p className="text-sm text-slate-500 dark:text-slate-400">
                自定义您的 Iroh Rig 体验
              </p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            {hasChanges && (
              <Badge variant="outline" className="text-orange-600 border-orange-600">
                有未保存的更改
              </Badge>
            )}
            <Button variant="outline" onClick={onClose}>
              关闭
            </Button>
          </div>
        </div>

        {/* 标签页 */}
        <Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as any)} className="flex-1 flex flex-col">
          <TabsList className="mx-6 mt-4 w-fit">
            <TabsTrigger value="general">常规</TabsTrigger>
            <TabsTrigger value="chat">聊天</TabsTrigger>
            <TabsTrigger value="appearance">外观</TabsTrigger>
            <TabsTrigger value="privacy">隐私</TabsTrigger>
            <TabsTrigger value="advanced">高级</TabsTrigger>
<TabsTrigger value="providers">提供商</TabsTrigger>
          </TabsList>

          {/* 常规设置 */}
          <TabsContent value="general" className="flex-1 p-6 pt-4 overflow-y-auto">
            <div className="space-y-6">
              <Card className="p-4">
                <h3 className="text-lg font-medium mb-4 flex items-center gap-2">
                  <Globe className="w-5 h-5" />
                  语言和地区
                </h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="language">界面语言</Label>
                    <select
                      id="language"
                      value={appSettings.language}
                      onChange={(e) => handleAppSettingChange('language', e.target.value)}
                      className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-md bg-white dark:bg-slate-800"
                    >
                      <option value="zh-CN">简体中文</option>
                      <option value="en-US">English</option>
                      <option value="ja-JP">日本語</option>
                    </select>
                  </div>
                  <div>
                    <Label htmlFor="fontSize">字体大小</Label>
                    <div className="flex items-center gap-3">
                      <Slider
                        value={[appSettings.fontSize]}
                        onValueChange={([value]) => handleAppSettingChange('fontSize', value)}
                        min={12}
                        max={20}
                        step={1}
                        className="flex-1"
                      />
                      <span className="text-sm text-slate-500 w-8">{appSettings.fontSize}px</span>
                    </div>
                  </div>
                </div>
              </Card>

              <Card className="p-4">
                <h3 className="text-lg font-medium mb-4 flex items-center gap-2">
                  <User className="w-5 h-5" />
                  用户体验
                </h3>
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>自动保存</Label>
                      <p className="text-sm text-slate-500">自动保存聊天记录和设置</p>
                    </div>
                    <Switch
                      checked={appSettings.autoSave}
                      onCheckedChange={(checked) => handleAppSettingChange('autoSave', checked)}
                    />
                  </div>
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>桌面通知</Label>
                      <p className="text-sm text-slate-500">接收重要消息的桌面通知</p>
                    </div>
                    <Switch
                      checked={appSettings.notifications}
                      onCheckedChange={(checked) => handleAppSettingChange('notifications', checked)}
                    />
                  </div>
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>声音效果</Label>
                      <p className="text-sm text-slate-500">播放消息提示音</p>
                    </div>
                    <Switch
                      checked={appSettings.soundEnabled}
                      onCheckedChange={(checked) => handleAppSettingChange('soundEnabled', checked)}
                    />
                  </div>
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>动画效果</Label>
                      <p className="text-sm text-slate-500">启用界面动画和过渡效果</p>
                    </div>
                    <Switch
                      checked={appSettings.animationsEnabled}
                      onCheckedChange={(checked) => handleAppSettingChange('animationsEnabled', checked)}
                    />
                  </div>
                </div>
              </Card>
            </div>
          </TabsContent>

          {/* 提供商设置 */}
          <TabsContent value="providers" className="flex-1 p-6 pt-4 overflow-y-auto">
            <ProviderSettingsSection />
          </TabsContent>

          {/* 聊天设置 */}
          <TabsContent value="chat" className="flex-1 p-6 pt-4 overflow-y-auto">
            <div className="space-y-6">
              <Card className="p-4">
                <h3 className="text-lg font-medium mb-4 flex items-center gap-2">
                  <Bot className="w-5 h-5" />
                  AI 模型设置
                </h3>
                <div className="space-y-4">
                  <div>
                    <Label htmlFor="maxTokens">最大令牌数</Label>
                    <div className="flex items-center gap-3">
                      <Slider
                        value={[chatSettings.maxTokens]}
                        onValueChange={([value]) => handleChatSettingChange('maxTokens', value)}
                        min={1000}
                        max={8000}
                        step={100}
                        className="flex-1"
                      />
                      <span className="text-sm text-slate-500 w-16">{chatSettings.maxTokens}</span>
                    </div>
                  </div>
                  <div>
                    <Label htmlFor="temperature">创造性 (Temperature)</Label>
                    <div className="flex items-center gap-3">
                      <Slider
                        value={[chatSettings.temperature]}
                        onValueChange={([value]) => handleChatSettingChange('temperature', value)}
                        min={0}
                        max={2}
                        step={0.1}
                        className="flex-1"
                      />
                      <span className="text-sm text-slate-500 w-8">{chatSettings.temperature}</span>
                    </div>
                  </div>
                </div>
              </Card>

              <Card className="p-4">
                <h3 className="text-lg font-medium mb-4">聊天界面</h3>
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>流式响应</Label>
                      <p className="text-sm text-slate-500">实时显示 AI 回复</p>
                    </div>
                    <Switch
                      checked={chatSettings.streamingEnabled}
                      onCheckedChange={(checked) => handleChatSettingChange('streamingEnabled', checked)}
                    />
                  </div>
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>自动滚动</Label>
                      <p className="text-sm text-slate-500">新消息时自动滚动到底部</p>
                    </div>
                    <Switch
                      checked={chatSettings.autoScroll}
                      onCheckedChange={(checked) => handleChatSettingChange('autoScroll', checked)}
                    />
                  </div>
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>显示时间戳</Label>
                      <p className="text-sm text-slate-500">在消息旁显示发送时间</p>
                    </div>
                    <Switch
                      checked={chatSettings.showTimestamps}
                      onCheckedChange={(checked) => handleChatSettingChange('showTimestamps', checked)}
                    />
                  </div>
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>紧凑模式</Label>
                      <p className="text-sm text-slate-500">减少消息间距</p>
                    </div>
                    <Switch
                      checked={chatSettings.compactMode}
                      onCheckedChange={(checked) => handleChatSettingChange('compactMode', checked)}
                    />
                  </div>
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>代码高亮</Label>
                      <p className="text-sm text-slate-500">启用代码语法高亮</p>
                    </div>
                    <Switch
                      checked={chatSettings.codeHighlighting}
                      onCheckedChange={(checked) => handleChatSettingChange('codeHighlighting', checked)}
                    />
                  </div>
                </div>
              </Card>
            </div>
          </TabsContent>

          {/* 外观设置 */}
          <TabsContent value="appearance" className="flex-1 p-6 pt-4 overflow-y-auto">
            <div className="space-y-6">
              <Card className="p-4">
                <h3 className="text-lg font-medium mb-4 flex items-center gap-2">
                  <Palette className="w-5 h-5" />
                  主题设置
                </h3>
                <div className="space-y-4">
                  <div>
                    <Label>主题模式</Label>
                    <div className="grid grid-cols-3 gap-3 mt-2">
                      {[
                        { value: 'light', label: '浅色' },
                        { value: 'dark', label: '深色' },
                        { value: 'system', label: '跟随系统' }
                      ].map((theme) => (
                        <button
                          key={theme.value}
                          onClick={() => handleAppSettingChange('theme', theme.value)}
                          className={`p-3 rounded-lg border-2 transition-colors ${
                            appSettings.theme === theme.value
                              ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                              : 'border-slate-200 dark:border-slate-700 hover:border-slate-300 dark:hover:border-slate-600'
                          }`}
                        >
                          <div className="text-sm font-medium">{theme.label}</div>
                        </button>
                      ))}
                    </div>
                  </div>
                </div>
              </Card>
            </div>
          </TabsContent>

          {/* 隐私设置 */}
          <TabsContent value="privacy" className="flex-1 p-6 pt-4 overflow-y-auto">
            <div className="space-y-6">
              <Card className="p-4">
                <h3 className="text-lg font-medium mb-4 flex items-center gap-2">
                  <Shield className="w-5 h-5" />
                  数据和隐私
                </h3>
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>数据收集</Label>
                      <p className="text-sm text-slate-500">允许收集匿名使用数据以改进产品</p>
                    </div>
                    <Switch
                      checked={privacySettings.dataCollection}
                      onCheckedChange={(checked) => handlePrivacySettingChange('dataCollection', checked)}
                    />
                  </div>
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>崩溃报告</Label>
                      <p className="text-sm text-slate-500">自动发送崩溃报告帮助修复问题</p>
                    </div>
                    <Switch
                      checked={privacySettings.crashReporting}
                      onCheckedChange={(checked) => handlePrivacySettingChange('crashReporting', checked)}
                    />
                  </div>
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>使用分析</Label>
                      <p className="text-sm text-slate-500">分享使用统计数据</p>
                    </div>
                    <Switch
                      checked={privacySettings.analytics}
                      onCheckedChange={(checked) => handlePrivacySettingChange('analytics', checked)}
                    />
                  </div>
                </div>
              </Card>
            </div>
          </TabsContent>

          {/* 高级设置 */}
          <TabsContent value="advanced" className="flex-1 p-6 pt-4 overflow-y-auto">
            <div className="space-y-6">
              <Card className="p-4">
                <h3 className="text-lg font-medium mb-4 flex items-center gap-2">
                  <Database className="w-5 h-5" />
                  数据管理
                </h3>
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>导出设置</Label>
                      <p className="text-sm text-slate-500">将当前设置导出为 JSON 文件</p>
                    </div>
                    <Button variant="outline" onClick={handleExportSettings}>
                      <Download className="w-4 h-4 mr-2" />
                      导出
                    </Button>
                  </div>
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>导入设置</Label>
                      <p className="text-sm text-slate-500">从 JSON 文件导入设置</p>
                    </div>
                    <div>
                      <input
                        type="file"
                        accept=".json"
                        onChange={handleImportSettings}
                        className="hidden"
                        id="import-settings"
                      />
                      <Button variant="outline" onClick={() => document.getElementById('import-settings')?.click()}>
                        <Upload className="w-4 h-4 mr-2" />
                        导入
                      </Button>
                    </div>
                  </div>
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>重置设置</Label>
                      <p className="text-sm text-slate-500">恢复所有设置到默认值</p>
                    </div>
                    <Button variant="outline" onClick={handleResetSettings}>
                      <RotateCcw className="w-4 h-4 mr-2" />
                      重置
                    </Button>
                  </div>
                </div>
              </Card>
            </div>
          </TabsContent>
        </Tabs>

        {/* 底部操作栏 */}
        <div className="flex items-center justify-between p-6 border-t border-slate-200 dark:border-slate-700">
          <div className="text-sm text-slate-500">
            {hasChanges ? '您有未保存的更改' : '所有更改已保存'}
          </div>
          <div className="flex gap-2">
            <Button variant="outline" onClick={onClose}>
              取消
            </Button>
            <Button onClick={handleSaveSettings} disabled={!hasChanges}>
              <Save className="w-4 h-4 mr-2" />
              保存设置
            </Button>
          </div>
        </div>
      </motion.div>
    </motion.div>
  );
}